/*
 * @Description: 水印控制
 */
import api from '@/api';

//父元素需要的定位
const PARENT_POSITION_LIST = ['relative', 'absolute', 'fixed'];

export function initWaterMark() {
    api.commonGetWaterMark('col')
      .then(({img}) => {
          waterMarkBase64 = img;
          hasNotWatermarkStyle = true;
      });
}
//标记是否添加了水印样式了
let hasNotWatermarkStyle = false;
let waterMarkBase64='';
async function check(el,wait=true) {
    let appType = 'col';
    if (!hasNotWatermarkStyle && wait) {
        setTimeout(() => check(el, false), 200);
    }
    //调接口获取
    const {img} = hasNotWatermarkStyle ? {img:waterMarkBase64} : await api.commonGetWaterMark(appType);
    //如果展示水印包含此区域，那么就展示
    if (img) {
        const { classList } = el;
        //如果父元素不包含指定定位,就设置为相对定位
        if (!PARENT_POSITION_LIST.includes(window.getComputedStyle(el).position)) {
            classList.add('relative');
        }
        //添加水印dom
        const watermarkEl = document.createElement('div');
        watermarkEl.setAttribute(
            'style',
            `position:absolute;top:0;bottom:0;left:0;right:0;z-index:99;pointer-events:none;background-image:url(${img});background-position-y:-30px;`
        );
        el.appendChild(watermarkEl);
        window.waterMarkBase64=img;
    }
}
export function getWaterMarkBase64(){
    return waterMarkBase64;
}

export default {
    install(Vue) {
        Vue.directive('watermark', {
            bind: check,
            // update: check,
        });
    },
};
